package com.hxzy.controller.admin;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hxzy.common.constans.RedisConstans;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.controller.BaseController;
import com.hxzy.dto.AdminLoginDTO;
import com.hxzy.exception.ValidatorException;
import com.hxzy.service.MallAdminUserService;
import com.hxzy.token.TokenService;
import com.hxzy.vo.AdminLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Api(tags = "后台管理用户登录/登出API")
@RestController
@RequestMapping(value = "/api/admin")
public class AdminLoginController extends BaseController {

    @Autowired
    private MallAdminUserService mallAdminUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "用户登录")
    @PostMapping(value = "/login")
    public R login(@RequestBody @Valid AdminLoginDTO adminLoginDTO){
        //验证验证码
        String redisKey= RedisConstans.getRedisKey(RedisConstans.CAPTCHA_KEY, adminLoginDTO.getUuid());
        Object redisValue=redisTemplate.opsForValue().get(redisKey);
        if(redisValue==null){
            throw new ValidatorException(AckCode.SMS_CODE_OVERTIME);
        }
        if(!redisValue.toString().equalsIgnoreCase(adminLoginDTO.getCode())){
            throw new ValidatorException(AckCode.SMS_CODE_WRONG);
        }
        //删除验证码
        this.redisTemplate.delete(redisKey);
        //查询用户
        AdminLoginVO adminLoginVO = this.mallAdminUserService.login(adminLoginDTO);
        //要把用户转换成jwt加密的令牌
        String token=this.tokenService.createJwtToken(adminLoginVO);
        return R.okHasData(token);
    }




    @ApiOperation(value = "获取当前用户登录信息")
    @GetMapping(value = "/info")
    public R getUserInfo() throws JsonProcessingException {
       // AdminLoginVO adminLoginVO = NewBeeThreadLocal.adminLoginVOThreadLocal.get();
       UsernamePasswordAuthenticationToken authenticationToken= (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
       AdminLoginVO adminLoginVO= (AdminLoginVO) authenticationToken.getPrincipal();
       return R.okHasData(adminLoginVO);
    }

}
